import QtQuick 2.6
import QtQuick.Layouts 1.3
import Qt.labs.controls 1.0
import Qt.labs.controls.universal 1.0

import fan.qt.complex 1.0 as Lex
import Qt.WebSockets 1.0

ApplicationWindow {
    id: window

    visible: true
    flags: Qt.FramelessWindowHint | Qt.Dialog
    visibility: "Maximized"

    property alias model: listview.model


    property alias initialItem: contentArea.initialItem
    property alias contentArea: contentArea

    signal quitApp()
    signal menuClicked()
    property alias actionMenu: actionMenu
    signal homeClicked()
    color: "grey"

    header: ToolBar {
        RowLayout {
            anchors.fill: parent
            spacing: 16

            ToolButton {
                id: actionMenu
                label: Image {
                    anchors.centerIn: parent
                    source:  contentArea.depth > 1 ? "../images/navigation_previous.png" : "../images/drawer.png"
                }

            }

            Label {
                text: window.title
                elide: Label.ElideRight

                verticalAlignment: Qt.AlignVCenter
                Layout.fillWidth: true
                font.pixelSize: 20
            }

            ToolButton {

                label: Image {
                    anchors.centerIn: parent
                    source: "qrc:/images/home.png"
                }
                onClicked: homeClicked()

            }

        }
    }

    function openDrawer() {
        drawer.open()
    }

    Drawer {
        id: drawer
        onClicked: close()

        Pane {
            padding: 0
            width: Math.min(window.width, window.height) / 3 * 2
            height: window.height
            ListView {
                id: listview

                anchors.fill: parent

                FontMetrics {
                    id: fontMetrics
                    font.family: window.font
                }


                footer: Rectangle {
                    width: listview.width
                    height: childrenRect.height

                    ColumnLayout {
                        spacing: 1
                        anchors.fill: parent

                        ToolButton{
                            text: "关于程序"
                            Layout.fillWidth: true
                            onClicked: {contentArea.navigate("../qml/AboutNavigator.qml")}
                            font.pixelSize: 14
                        }


                        ToolButton {
                            text: "意见反馈"
                            Layout.fillWidth: true
                            onClicked: {contentArea.navigate("../qml/FeedbackNavigator.qml")}
                            font.pixelSize: 14
                        }

                        ToolButton{
                            id: quit
                            text: "退出"
                            Layout.fillWidth: true
                            onClicked: quitApp()
                            font.pixelSize: 14
                        }

                    }
                }
            }
        }
    }

    StackArea{
        id: contentArea
        anchors.fill: parent
    }
    property string serverUrl: "127.0.0.1"
    property string token: Lex.A.newGUID()


    function delayRun(interval, param, callback){
        if (callback instanceof Function) {
            var delayTimer = Qt.createQmlObject('import QtQuick 2.6; Timer {property var trigger;property var param;onTriggered: trigger(param);}', contentArea);
            delayTimer.interval = interval;
            delayTimer.trigger = callback;
            delayTimer.param = param;
            delayTimer.triggered.connect(function(){delayTimer.destroy()});
            delayTimer.repeat = false;
            delayTimer.start();
        }
    }


    property var http: QtObject {
        readonly property string url: "http://" +  Lex.G.SERVER + "/routes/api"
        function build(path, query) {
            return url + additionalPath(path, query)
        }

        function request(path, m, d, c)
        {
            var doc = new XMLHttpRequest();

            doc.onreadystatechange = function() {
                if (doc.readyState === XMLHttpRequest.DONE) {
                    console.log("status:", doc.status, "-", doc.statusText)


                    if (doc.status != 200) {
                      // 网络错误
                    }

                    var ch = doc.responseText.charAt(0)

                    if (ch == '<') {
                        c(doc.responseXML);
                    } else if ( ch == '{' || ch == '[' ){
                        console.log("#-------------------------")
                        console.log(doc.responseText)

                        console.log("#-------------------------")

                       c(JSON.parse(doc.responseText))
                    }
                }
            }

            console.info("#", url + path)
            doc.open(m.toUpperCase(), url + path);
            doc.setRequestHeader('Content-Type', 'application/json')

            switch (m.toUpperCase()) {
            case "POST":
            case "PUT":
                doc.send(JSON.stringify(d))
                console.info("# body: ", JSON.stringify(d))
                break;
            default:
                doc.send()
            }
        }

        function additionalPath(path, query) {
            query.token = Qt.md5(usinfo.token).toUpperCase()


            Object.keys(query).forEach(function(k) {
               Lex.U.addQueryItem(k, query[k])
            })

            var c = "?"
           if (path.indexOf("?")  !== -1) {
                c = "&"
           }

           path +=  c + Lex.U.toEncodedString()

            Lex.U.clear()

            return path
        }

        function get(path, query, callback) {
            request(additionalPath(path, query), "GET", data, callback)
        }

        function put(path, query, data, callback) {
            request(additionalPath(path, query), "PUT", data, callback)
        }
        function post(path, query, data, callback) {
            request(additionalPath(path, query), "POST", data, callback)
        }

        function del(path, query, callback) {
            request(additionalPath(path, query), "DELETE", data, callback)
        }

    }

    property var dialog: QtObject {
        id: o7


        function message(text)
        {
              var component = Qt.createComponent(Qt.resolvedUrl("../template/MessageText.qml"), contentArea);

            if (component.status === Component.Ready) {
                var i = component.createObject(contentArea,  {"text": text});
                i.open()
            }
            else {
                console.error("create component error: " + component.errorString());
            }

        }

        function toast(text)
        {
            var component = Qt.createComponent(Qt.resolvedUrl("../template/Toast.qml"), contentArea);

          if (component.status === Component.Ready) {
              var i = component.createObject(contentArea,  {"text": text});
              i.open()
          }
          else {
              console.error("create component error: " + component.errorString());
          }


        }

    }
    property var network: QtObject {
        id: __network
        property var binding: ({})



        // not supported recursive
        function request(address, action, data, triggered, resident)
        {
            delete binding[action];

            if (!triggered) {triggered = function(){};}
            if (isNaN(resident)) resident = 1

            binding[action] = {triggered: triggered, resident: resident};

            if (!address)
                Ws.post(action, data)
            else {
                Udp.post(address, {action: action, data: data})
            }
        }

        function bindNotify(action, triggered) {
            binding[action] = {triggered: triggered, resident: -1};
        }

        function delNotify(action) {
            delete binding[action];
        }

        function dispatch(address, action, data)
        {
            if (binding.hasOwnProperty(action))
            {
                binding[action].triggered(data, address);

                if (binding[action].resident > 0) {
                    binding[action].resident = binding[action].resident - 1
                }

                if (binding[action].resident === 0)
                    delete binding[action];
            }
        }

    }
}
